import pandas as pd
import numpy as np
from utils.logger import logger

class Strategy1:
    def __init__(self):
        self.short_window = 20
        self.long_window = 50
        self.signals = []

    def on_bars(self, data):  
        data = self.strategy_mv(data)
        
    
    def strategy_mv(self, data):
        # 将日期列转换为日期格式
        data['Date'] = pd.to_datetime(data['datetime'])

        # 设置日期列为索引
        data.set_index('Date', inplace=True)

        # 计算短期和长期移动平均线
        data['short_mavg'] = data['close'].rolling(window=self.short_window).mean()
        data['long_mavg'] = data['close'].rolling(window=self.long_window).mean()

        # 生成交易信号
        # 上穿卖出 下穿买入
        data['signal'] = np.where(data['short_mavg'] > data['long_mavg'], -1, 0)
        data['signal'] = np.where(data['short_mavg'] < data['long_mavg'], 1, 0)
        data['positions'] = data['signal'].diff()

        # 计算策略的每日收益率
        data['returns'] = data['close'].pct_change()
        data['strategy_returns'] = data['returns'] * data['positions'].shift(1)

        # 计算累计收益率
        data['cumulative_returns'] = (1 + data['strategy_returns']).cumprod()

        return data

